<template>
  <div class="exchange-shop">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1>积分兑换商城</h1>
        <p>用积分兑换精美商品和优惠券</p>
        <div class="user-points">
          <i class="el-icon-coin"></i>
          <span>我的积分：{{ userPoints }}</span>
        </div>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-content">
        <div class="filter-item">
          <label>商品分类：</label>
          <el-select v-model="filters.category" placeholder="全部分类" clearable @change="loadProducts">
            <el-option label="全部分类" value=""></el-option>
            <el-option label="实物商品" value="PHYSICAL"></el-option>
            <el-option label="优惠券" value="DISCOUNT_COUPON"></el-option>
            <el-option label="免邮券" value="FREE_SHIPPING"></el-option>
            <el-option label="虚拟商品" value="VIRTUAL"></el-option>
          </el-select>
        </div>
        
        <div class="filter-item">
          <label>商品类型：</label>
          <el-select v-model="filters.productType" placeholder="全部类型" clearable @change="loadProducts">
            <el-option label="全部类型" value=""></el-option>
            <el-option label="折扣券" value="DISCOUNT_COUPON"></el-option>
            <el-option label="免邮券" value="FREE_SHIPPING"></el-option>
            <el-option label="实物商品" value="PHYSICAL"></el-option>
            <el-option label="虚拟商品" value="VIRTUAL"></el-option>
          </el-select>
        </div>
        
        <div class="filter-item">
          <el-input
            v-model="filters.name"
            placeholder="搜索商品名称"
            @keyup.enter="loadProducts"
            @clear="loadProducts"
            clearable
          >
            <el-button slot="append" @click="loadProducts"></el-button>
          </el-input>
        </div>
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="products-section">
      <div class="products-grid" v-loading="loading">
        <div
          v-for="product in products"
          :key="product.id"
          class="product-card"
          @click="showProductDetail(product)"
        >
          <div class="product-image">
            <img :src="product.imageUrl || '/src/assets/logo.png'" :alt="product.name">
            <div class="product-badge" v-if="product.isHot">热门</div>
          </div>
          
          <div class="product-info">
            <h3 class="product-name">{{ product.name }}</h3>
            <p class="product-desc">{{ product.description }}</p>
            
            <div class="product-price">
              <div class="points-price">
                <i class="el-icon-coin"></i>
                <span>{{ product.pointsRequired }}</span>
              </div>
              <div class="original-price" v-if="product.originalPrice">
                <span>原价：¥{{ product.originalPrice }}</span>
              </div>
            </div>
            
            <div class="product-stock">
              <span v-if="product.stockQuantity > 0">库存：{{ product.stockQuantity }}</span>
              <span v-else class="out-of-stock">已售罄</span>
            </div>
            
            <div class="product-actions">
              <el-button
                type="primary"
                size="small"
                @click.stop="showExchangeDialog(product)"
                :disabled="product.stockQuantity === 0 || userPoints < product.pointsRequired"
              >
                {{ product.stockQuantity === 0 ? '已售罄' : '立即兑换' }}
              </el-button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
        />
      </div>
    </div>

    <!-- 兑换对话框 -->
    <el-dialog
      title="确认兑换"
      :visible.sync="exchangeDialogVisible"
      width="500px"
      @close="resetExchangeDialog"
    >
      <div class="exchange-dialog-content" v-if="selectedProduct">
        <div class="product-summary">
          <img :src="selectedProduct.imageUrl || '/src/assets/logo.png'" :alt="selectedProduct.name">
          <div class="product-details">
            <h4>{{ selectedProduct.name }}</h4>
            <p>{{ selectedProduct.description }}</p>
            <div class="price-info">
              <span class="points-required">所需积分：{{ selectedProduct.pointsRequired * exchangeQuantity }}</span>
              <span class="original-price" v-if="selectedProduct.originalPrice">
                原价：¥{{ selectedProduct.originalPrice * exchangeQuantity }}
              </span>
            </div>
          </div>
        </div>
        
        <div class="quantity-selector">
          <label>兑换数量：</label>
          <el-input-number
            v-model="exchangeQuantity"
            :min="1"
            :max="Math.min(selectedProduct.stockQuantity, Math.floor(userPoints / selectedProduct.pointsRequired))"
            @change="updateExchangeTotal"
          />
        </div>
        
        <div class="exchange-summary">
          <p>消耗积分：<span class="highlight">{{ selectedProduct.pointsRequired * exchangeQuantity }}</span></p>
          <p>剩余积分：<span class="highlight">{{ userPoints - selectedProduct.pointsRequired * exchangeQuantity }}</span></p>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="exchangeDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="confirmExchange"
          :loading="exchanging"
          :disabled="!selectedProduct || userPoints < selectedProduct.pointsRequired * exchangeQuantity"
        >
          确认兑换
        </el-button>
      </div>
    </el-dialog>

    <!-- 商品详情对话框 -->
    <el-dialog
      title="商品详情"
      :visible.sync="detailDialogVisible"
      width="600px"
    >
      <div class="product-detail-content" v-if="selectedProduct">
        <div class="detail-image">
          <img :src="selectedProduct.imageUrl || '/src/assets/logo.png'" :alt="selectedProduct.name">
        </div>
        
        <div class="detail-info">
          <h3>{{ selectedProduct.name }}</h3>
          <p class="detail-description">{{ selectedProduct.description }}</p>
          
          <div class="detail-price">
            <div class="points-price">
              <i class="el-icon-coin"></i>
              <span>{{ selectedProduct.pointsRequired }} 积分</span>
            </div>
            <div class="original-price" v-if="selectedProduct.originalPrice">
              <span>原价：¥{{ selectedProduct.originalPrice }}</span>
            </div>
          </div>
          
          <div class="detail-stock">
            <span v-if="selectedProduct.stockQuantity > 0">库存：{{ selectedProduct.stockQuantity }}</span>
            <span v-else class="out-of-stock">已售罄</span>
          </div>
          
          <div class="detail-attributes" v-if="selectedProduct.validityDays">
            <p>有效期：{{ selectedProduct.validityDays }} 天</p>
          </div>
          
          <div class="detail-actions">
            <el-button
              type="primary"
              @click="showExchangeDialog(selectedProduct)"
              :disabled="selectedProduct.stockQuantity === 0 || userPoints < selectedProduct.pointsRequired"
            >
              {{ selectedProduct.stockQuantity === 0 ? '已售罄' : '立即兑换' }}
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'ExchangeShop',
  data() {
    return {
      loading: false,
      exchanging: false,
      userPoints: 0,
      products: [],
      total: 0,
      currentPage: 1,
      pageSize: 12,
      filters: {
        category: '',
        productType: '',
        name: ''
      },
      exchangeDialogVisible: false,
      detailDialogVisible: false,
      selectedProduct: null,
      exchangeQuantity: 1
    }
  },
  mounted() {
    this.loadUserPoints()
    this.loadProducts()
  },
  methods: {
    // 加载用户积分
    async loadUserPoints() {
      try {
        const user = JSON.parse(localStorage.getItem('user'))
        if (user && user.id) {
          const response = await request.get(`/api/member/points/available/${user.id}`)
          if (response.code === '200') {
            this.userPoints = response.data || 0
          }
        }
      } catch (error) {
        console.error('加载用户积分失败:', error)
      }
    },
    
    // 加载商品列表
    async loadProducts() {
      this.loading = true
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          ...this.filters
        }
        
        const response = await request.get('/api/member/exchange/products', { params })
        if (response.code === '200') {
          this.products = response.data.records || []
          this.total = response.data.total || 0
        } else {
          this.$message.error(response.msg || '加载商品列表失败')
        }
      } catch (error) {
        console.error('加载商品列表失败:', error)
        this.$message.error('加载商品列表失败')
      } finally {
        this.loading = false
      }
    },
    
    // 分页切换
    handleCurrentChange(page) {
      this.currentPage = page
      this.loadProducts()
    },
    
    // 显示商品详情
    showProductDetail(product) {
      this.selectedProduct = product
      this.detailDialogVisible = true
    },
    
    // 显示兑换对话框
    showExchangeDialog(product) {
      this.selectedProduct = product
      this.exchangeQuantity = 1
      this.exchangeDialogVisible = true
      this.detailDialogVisible = false
    },
    
    // 重置兑换对话框
    resetExchangeDialog() {
      this.selectedProduct = null
      this.exchangeQuantity = 1
    },
    
    // 更新兑换总计
    updateExchangeTotal() {
      // 这里可以添加更多逻辑
    },
    
    // 确认兑换
    async confirmExchange() {
      if (!this.selectedProduct) return
      
      this.exchanging = true
      try {
        const user = JSON.parse(localStorage.getItem('user'))
        if (!user || !user.id) {
          this.$message.error('请先登录')
          return
        }
        
        const response = await request.post('/api/member/exchange/products/exchange', {
          userId: user.id,
          productId: this.selectedProduct.id,
          quantity: this.exchangeQuantity
        })
        
        if (response.code === '200') {
          this.$message.success('兑换成功！兑换码：' + response.data)
          this.exchangeDialogVisible = false
          this.loadUserPoints()
          this.loadProducts()
        } else {
          this.$message.error(response.msg || '兑换失败')
        }
      } catch (error) {
        console.error('兑换失败:', error)
        this.$message.error('兑换失败')
      } finally {
        this.exchanging = false
      }
    }
  }
}
</script>

<style scoped>
.exchange-shop {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 40px 0;
  text-align: center;
}

.header-content h1 {
  font-size: 2.5rem;
  margin-bottom: 10px;
  font-weight: 300;
}

.header-content p {
  font-size: 1.2rem;
  margin-bottom: 20px;
  opacity: 0.9;
}

.user-points {
  display: inline-flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.2);
  padding: 10px 20px;
  border-radius: 25px;
  font-size: 1.1rem;
  font-weight: 500;
}

.user-points i {
  margin-right: 8px;
  font-size: 1.2rem;
}

.filter-section {
  background: white;
  padding: 20px 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.filter-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 0 20px;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-item label {
  font-weight: 500;
  white-space: nowrap;
}

.products-section {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.product-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.product-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  background: #ff4757;
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 0.8rem;
}

.product-info {
  padding: 20px;
}

.product-name {
  font-size: 1.2rem;
  font-weight: 600;
  margin-bottom: 8px;
  color: #333;
}

.product-desc {
  color: #666;
  font-size: 0.9rem;
  margin-bottom: 15px;
  line-height: 1.4;
}

.product-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.points-price {
  display: flex;
  align-items: center;
  color: #e74c3c;
  font-weight: 600;
  font-size: 1.1rem;
}

.points-price i {
  margin-right: 5px;
}

.original-price {
  color: #999;
  font-size: 0.9rem;
  text-decoration: line-through;
}

.product-stock {
  margin-bottom: 15px;
  font-size: 0.9rem;
  color: #666;
}

.out-of-stock {
  color: #e74c3c;
  font-weight: 500;
}

.product-actions {
  text-align: center;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.exchange-dialog-content {
  padding: 20px 0;
}

.product-summary {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.product-summary img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 8px;
}

.product-details h4 {
  margin-bottom: 10px;
  color: #333;
}

.price-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.points-required {
  color: #e74c3c;
  font-weight: 600;
}

.quantity-selector {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
}

.exchange-summary {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #667eea;
}

.exchange-summary p {
  margin-bottom: 5px;
  display: flex;
  justify-content: space-between;
}

.highlight {
  color: #e74c3c;
  font-weight: 600;
}

.product-detail-content {
  display: flex;
  gap: 30px;
}

.detail-image {
  flex: 0 0 300px;
}

.detail-image img {
  width: 100%;
  height: 300px;
  object-fit: cover;
  border-radius: 8px;
}

.detail-info {
  flex: 1;
}

.detail-info h3 {
  font-size: 1.5rem;
  margin-bottom: 15px;
  color: #333;
}

.detail-description {
  color: #666;
  line-height: 1.6;
  margin-bottom: 20px;
}

.detail-price {
  margin-bottom: 15px;
}

.detail-stock {
  margin-bottom: 15px;
}

.detail-attributes {
  margin-bottom: 20px;
  color: #666;
}

.detail-actions {
  margin-top: 20px;
}

@media (max-width: 768px) {
  .filter-content {
    flex-direction: column;
    gap: 15px;
  }
  
  .products-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  }
  
  .product-detail-content {
    flex-direction: column;
  }
  
  .detail-image {
    flex: none;
  }
}
</style> 